package cshi.common;


import java.util.Random;


public class Utils {
	public static byte[] int2bytes(int num){
		// small endian
		byte[] result = new byte[4];
		result[0] = (byte)(num & 0xff);
		result[1] = (byte)((num >> 8) & 0xff);
		result[2] = (byte)((num >> 16) & 0xff);
		result[3] = (byte)(num >>> 24);
		
		/*
		// big endian
		result[0] = (byte)((num >>> 24) & 0xff);
		result[1] = (byte)((num >>> 16)& 0xff );
		result[2] = (byte)((num >>> 8) & 0xff );
		result[3] = (byte)((num >>> 0) & 0xff );
		*/
		return result;
	}
	
	public static void int2bytes(int n,byte[] arr ,int offset){
		arr[0+offset] = (byte) (n & 0xff);
        arr[1+offset] = (byte) (n >> 8 & 0xff);
        arr[2+offset] = (byte) (n >> 16 & 0xff);
        arr[3+offset] = (byte) (n >> 24 & 0xff);
	}
	
	public static int bytes2int(byte[] arr) {
		return bytes2int(arr, 0);
	}
	
	public static int bytes2int(byte[] arr,int offset) {
		return arr[0+offset] & 0xff
				| (arr[1+offset] & 0xff) << 8
				| (arr[2+offset] & 0xff) << 16
				| (arr[3+offset] & 0xff) << 24;
	}
	
	public static void printByteArray(byte[] data) {
		int cnt = 0;
		for (byte i:data) {
			System.out.format("%2x  ", i);
			cnt++;
			if (cnt == 20) {
				System.out.println();
				cnt = 0;
			}
		}
		System.out.println();
	}
	
	public static void print(String str) {
		System.out.println(str);
	}
	
	public static void print(int i) {
		System.out.println(i);
	}
		
	public static void print() {
		System.out.println();
	}
	
	public static String getRandomString(int length) { 
	    String base = "abcdefghijklmnopqrstuvwxyz0123456789";   
	    Random random = new Random();   
	    StringBuffer sb = new StringBuffer();   
	    for (int i = 0; i < length; i++) {   
	        int number = random.nextInt(base.length());   
	        sb.append(base.charAt(number));   
	    }   
	    return sb.toString();   
	 }   

	public static String getRandomString(String unit,int repeat) { 
	    StringBuffer sb = new StringBuffer();   
	    for (int i = 0; i < repeat; i++) {   
	        sb.append(unit);
	    }   
	    return sb.toString();   
	 }   
	
	public static String toMemoryInfo() {
	       Runtime currRuntime = Runtime.getRuntime ();
	       int nFreeMemory = ( int ) (currRuntime.freeMemory() / 1024 / 1024);
	       int nTotalMemory = ( int ) (currRuntime.totalMemory() / 1024 / 1024);
	       return nFreeMemory + "M/" + nTotalMemory +"M(free/total)" ;
	}
	
	public static void main(String[] args) {
		print(toMemoryInfo());
	}
}
